package com.ffe.flower.engine.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ffe.flower.engine.constant.AuditStatus;
import com.ffe.flower.engine.dao.FlowStateDetailDao;
import com.ffe.flower.engine.model.FlowStateDetail;
import com.ffe.flower.engine.service.IFlowStateDetailService;
import com.ffe.flower.engine.wrapper.FlowStateWrapper;

@Transactional
@Service
public class FlowStateDetailServiceImpl implements IFlowStateDetailService {

  @Autowired
  private FlowStateDetailDao flowStateDetailDao;

  @Override
  public List<FlowStateWrapper> getWholeFlowState(Integer flowId) {
    return flowStateDetailDao.findByFlowIdOrderByStateIdAsc(flowId).stream().map(FlowStateWrapper::new)
        .collect(Collectors.toList());
  }

  @Override
  public FlowStateDetail add(FlowStateDetail flowState) {
    return flowStateDetailDao.save(flowState);
  }

  @Override
  public FlowStateDetail get(Integer stateId) {
    return flowStateDetailDao.findById(stateId).orElse(null);
  }

  @Override
  public FlowStateDetail create(Integer flowId, Enum<?> flowState) {
    FlowStateDetail newFlowState = new FlowStateDetail();
    newFlowState.setFlowState(flowState);
    newFlowState.setFlowId(flowId);
    newFlowState.setAuditStatus(AuditStatus.PENDING);
    add(newFlowState);
    return newFlowState;
  }

  @Override
  public FlowStateDetail complete(Integer curFlowId, AuditStatus auditStatus, String auditorId, boolean auditorAgent,
      String remark) {
    FlowStateDetail flowState = get(curFlowId);
    flowState.setAuditStatus(auditStatus);
    flowState.setAuditorId(auditorId);
    flowState.setAuditorAgent(auditorAgent);
    flowState.setRemark(remark);
    add(flowState);
    return flowState;
  }

}
